const jwt = require('jsonwebtoken');
const db = require('../config/database');
const logger = require('../utils/logger');

// JWT配置
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

// 生成Token
const generateToken = (userId) => {
  return jwt.sign(
    { userId },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  );
};

// 验证Token - 用户端
const authenticateUserToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失，请登录'
      });
    }

    // 验证JWT
    const decoded = jwt.verify(token, JWT_SECRET);

    // 查询用户信息
    const [users] = await db.query(
      'SELECT id, username, nickname, phone, is_guest, status FROM users WHERE id = ? AND status = 1',
      [decoded.userId]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      });
    }

    // 将用户信息添加到请求对象
    req.user = users[0];
    next();
  } catch (error) {
    logger.error('JWT验证失败:', error);

    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: '访问令牌已过期，请重新登录'
      });
    }

    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        success: false,
        message: '无效的访问令牌'
      });
    }

    return res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
};

// 可选的Token验证 - 允许游客模式
const optionalAuthenticateToken = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      // 没有token，允许游客访问
      req.user = null;
      return next();
    }

    // 有token，进行验证
    const decoded = jwt.verify(token, JWT_SECRET);

    const [users] = await db.query(
      'SELECT id, username, nickname, phone, is_guest, status FROM users WHERE id = ? AND status = 1',
      [decoded.userId]
    );

    if (users.length > 0) {
      req.user = users[0];
    } else {
      req.user = null;
    }

    next();
  } catch (error) {
    // Token验证失败，但允许游客访问
    req.user = null;
    next();
  }
};

module.exports = {
  generateToken,
  authenticateUserToken,
  optionalAuthenticateToken,
  authenticateAdminToken: authenticateUserToken, // 管理员使用相同的认证（可通过用户角色扩展）
  JWT_SECRET,
  JWT_EXPIRES_IN
};

